import { ref } from 'vue'

type Callback = (data?: any) => void

class EventBus {
    private events = ref<{ [key: string]: Callback[] }>({})

    emit(event: string, data?: any) {
        if (this.events.value[event]) {
            this.events.value[event].forEach(callback => callback(data))
        }
    }

    on(event: string, callback: Callback) {
        if (!this.events.value[event]) {
            this.events.value[event] = []
        }
        this.events.value[event].push(callback)
    }

    off(event: string, callback?: Callback) {
        if (!this.events.value[event]) return

        if (callback) {
            const index = this.events.value[event].indexOf(callback)
            if (index > -1) {
                this.events.value[event].splice(index, 1)
            }
        } else {
            delete this.events.value[event]
        }
    }
}

export const eventBus = new EventBus()